<?php
/**
 * Created by PhpStorm.
 * User: zhangyajie
 * Date: 2020/11/11
 * Time: 16:53
 */

namespace App\Utils;

use MQ\Model\TopicMessage;
use MQ\MQClient;

class MqProducer
{
    private $client;
    private $producer;
    public $accessKeyId = 'LTAI4GFyQ2yRnTG4UKGXcUwq';
    public $accessSecret = 'bJ893KlddGsn7ZViGHTwqztjevubZn';
    public $instanceId = 'MQ_INST_50112006_BXYle0HK';
    public $host = 'http://50112006.mqrest.cn-beijing.aliyuncs.com';

    public function __construct()
    {
        $this->client = new MQClient($this->host, $this->accessKeyId, $this->accessSecret);

        $topic = "test";
        $this->producer = $this->client->getProducer($this->instanceId, $topic);
    }

    public function run()
    {
        try
        {
            for ($i=1; $i<=5; $i++)
            {
                $publishMessage = new TopicMessage(
                    "this is test message----".$i // 消息内容
                );
                // 设置属性
                $publishMessage->putProperty("a", $i);
                // 设置消息KEY
                $publishMessage->setMessageKey("MessageKey");
//                if ($i % 2 == 0) {
//                    // 定时消息, 定时时间为10s后
//                    $publishMessage->setStartDeliverTime(time() * 1000 + 10 * 1000);
//                }
                $result = $this->producer->publishMessage($publishMessage);

                print "Send mq message success. msgId is:" . $result->getMessageId() . ", bodyMD5 is:" . $result->getMessageBodyMD5() . "\r\n";

                // 设置换行
                echo "<br>";
            }
        } catch (\Exception $e) {
            print_r($e->getMessage() . "\n");
        }
    }
}
